package top.yxqz.servletcontext;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Mr.余
 * @date 2022/11/14
 * @package top.yxqz.servletcontext
 * ServletContext对象是通过ServletConfig来获取的
 */
public class ServletContextDemo01 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        得到ServletConfig对象
        ServletConfig config = getServletConfig();
//        通过ServletConfig对象得到ServletContext对象
        ServletContext context = config.getServletContext();

//        解决中文乱码问题
        String req_encoding = context.getInitParameter("req_encoding");
        String resp_encoding = context.getInitParameter("resp_encoding");
        request.setCharacterEncoding(req_encoding);
        response.setContentType(resp_encoding);

//      相应给前端，以html的方式
        PrintWriter writer = response.getWriter();
        writer.print("请求编码："+req_encoding);
        writer.print("<hr>");
        writer.print("相应编码："+resp_encoding);

    }
}
